//
//  VideoCachePlayer.swift
//  ANOASTORE
//
//  Created by hudan on 2025/5/13.
//  Copyright © 2025 zwb. All rights reserved.
//

import UIKit
import AVKit

class VideoCachePlayer: UIViewController {
    var videoURL: URL!
    private var playerViewController: AVPlayerViewController!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        playVideo(with: videoURL)
    }
    
    // 获取本地缓存路径
    private func localFilePath(for url: URL) -> URL {
        let fileName = url.absoluteString.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? UUID().uuidString
        let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        return documents.appendingPathComponent(fileName + ".mp4")
    }
    
    // 检查本地是否有缓存
    private func cachedVideoURL(for url: URL) -> URL? {
        let localURL = localFilePath(for: url)
        if FileManager.default.fileExists(atPath: localURL.path) {
            return localURL
        }
        return nil
    }
    
    // 下载并缓存视频
    private func downloadVideo(from url: URL) {
        let localURL = localFilePath(for: url)
        if FileManager.default.fileExists(atPath: localURL.path) {
            return
        }
        let task = URLSession.shared.downloadTask(with: url) { tempURL, response, error in
            guard let tempURL = tempURL, error == nil else { return }
            do {
                try FileManager.default.moveItem(at: tempURL, to: localURL)
            } catch {
                // 处理文件移动失败
            }
        }
        task.resume()
    }
    
    // 播放视频
    private func playVideo(with url: URL) {
        var playURL = url
        if let cached = cachedVideoURL(for: url) {
            playURL = cached
        } else {
            downloadVideo(from: url)
        }
        let player = AVPlayer(url: playURL)
        playerViewController = AVPlayerViewController()
        playerViewController.player = player
        playerViewController.view.frame = self.view.bounds
        self.addChild(playerViewController)
        self.view.addSubview(playerViewController.view)
        playerViewController.didMove(toParent: self)
        player.play()
    }
}
